package cn.edu.hy.demo04.dao;

import cn.edu.hy.demo04.model.User;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class UserDao {

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * 新增用户
     * @param user
     */
    public void addUser(User user) {
        //调用jdbc模板去操作数据库的新增
        String insertSql = "insert into user values(?,?,?)";
        jdbcTemplate.update(insertSql,new Object[]{user.getId(),user.getUserName(),user.getPassWord()});
    }

    /**
     * 查询用户
     * @param user
     * @return
     */
    public List<User> findUserList(User user) {

        String selectSql = "select * from user";
        List<User> users = new ArrayList<>();
        List<Map<String,Object>> res = jdbcTemplate.queryForList(selectSql);
        for (Map<String,Object> m:res){
            User ruser = new User();
            ruser.setId((String) m.get("id"));
            ruser.setUserName((String) m.get("username"));
            ruser.setPassWord((String) m.get("password"));
            users.add(ruser);
        }
        return users;
    }
}
